The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a number with this property is 614656 = 284.

We shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum.

You are given that a2 = 512 and a10 = 614656.

Find a30.


In [1]:
512.to_s.split("").map{|i|i.to_i}.inject(:+)**(512.to_s.length)


Out[1]:
512

In [58]:
def check_dps(num)
  base = num.to_s.split("").map{|k|k.to_i}.inject(:+)
  (2..99).each do |i|
    target = base ** i
    return true if num == target
    return false if num < target
  end
  
  return false
end

check_dps(512)


Out[58]:
true

In [59]:
check_dps 614656


Out[59]:
true

In [60]:
result = []

(11..614656).lazy.each do |num| 
  result << num if check_dps(num)
end

puts result


[0, 1, 81, 512, 2401, 4913, 5832, 17576, 19683, 234256, 390625, 614656, 1679616]

In [62]:
def find_target
  result = []
  (2..99).each{|k| result = result + (2..10).map{|i|k**i}}
  result
end

find_target.length


Out[62]:
882

In [69]:
result = []

find_target.uniq.sort.each do |num| 
  result << num if check_dps(num)
end

puts result.sort


[81, 512, 2401, 4913, 5832, 17576, 19683, 234256, 390625, 614656, 1679616, 17210368, 34012224, 52521875, 60466176, 205962976, 612220032, 8303765625, 10460353203, 24794911296, 27512614111, 52523350144, 68719476736, 271818611107, 1174711139837, 2207984167552, 6722988818432, 20047612231936, 72301961339136, 248155780267521, 3904305912313344, 45848500718449031, 150094635296999121, 13744803133596058624, 19687440434072265625, 53861511409489970176, 73742412689492826049]

In [68]:
result[29]


Out[68]:
248155780267521

In [ ]: